﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NUS.ISS.ARS.Web.PageController;
using NUS.ISS.ARS.BusinessEntity.ViewModels;

namespace NUS.ISS.ARS.Web.Booking
{
    public partial class SelectFlight : BookingBaseController
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CurrentPage = "SelectFlight.aspx";
            base.Page_Load(sender, e);

            if (!Page.IsPostBack)
            {
                btnPre.Visible = IsPrePageVisible;
                btnNext.Visible = IsNextPageVisible;
                BindData();
            }
        }

        private void BindData()
        {
            if (FlightBookingTrips.Count() > 0)
            {
                ////Remove the currently booked flights
                //var otherFlightBookingTrips = FlightBookingTrips.Where(t => t.ToBeChanged != true);

                lblDestTitle.Text = ReservationData.FromCityName + " to " + ReservationData.ToCityName;

                if (ReservationData.IsRoundTrip == false)
                {
                    lvFlightsToDest.DataSource = OtherFlightBookingTrips;
                    lvFlightsToDest.DataBind();
                }
                else //round trip
                {
                    lvFlightsToDest.DataSource = OtherFlightBookingTrips.Where(t => t.FromCityId == ReservationData.FromCityId);
                    lvFlightsToDest.DataBind();

                    lblReturnTitle.Text = ReservationData.ToCityName + " to " + ReservationData.FromCityName;
                    lvReturnFlights.DataSource = OtherFlightBookingTrips.Where(t => t.FromCityId == ReservationData.ToCityId);
                    lvReturnFlights.DataBind();
                }                
                
                SetSelectedTripFromSession();
            }
            else
            {
                lblMsg.Text = "No flights found.";
            }
        }

        private void SetSelectedTripFromSession()
        {
            if (ReservationData.SelectedBookingTrips != null && ReservationData.SelectedBookingTrips.Count() > 0)
            {
                foreach (var item in lvFlightsToDest.Items)
                {
                    long flightSchId = 0;
                    DateTime flightDate = DateTime.MinValue;
                    var radioButton = item.FindControl("rdoSelectDestFlight") as RadioButton;
                    long.TryParse(((Label)item.FindControl("lblFlighSchedueId")).Text, out flightSchId);
                    DateTime.TryParse(((Label)item.FindControl("lblFlightDate")).Text, out flightDate);

                    if (flightSchId == ReservationData.SelectedBookingTrips.ToArray()[0].FlightScheduleId
                        && flightDate == ReservationData.SelectedBookingTrips.ToArray()[0].FlightDate)
                    {
                        radioButton.Checked = true;
                    }
                    else
                    {
                        string clearRadioButtonscript = String.Format("<script type='text/javascript'>$(document).ready(function() {{$('#{0}').prop('checked', false);}});</script>"
                            ,radioButton.ClientID);
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "clearDestFlightRadioButtonscript", clearRadioButtonscript);
                    }
                }

                if (ReservationData.IsRoundTrip)
                {
                    foreach (var item in lvReturnFlights.Items)
                    {
                        long flightSchId = 0;
                        DateTime flightDate = DateTime.MinValue;
                        var radioButton = item.FindControl("rdoSelectReturnFlight") as RadioButton;
                        long.TryParse(((Label)item.FindControl("lblFlighSchedueId")).Text, out flightSchId);
                        DateTime.TryParse(((Label)item.FindControl("lblFlightDate")).Text, out flightDate);

                        if (flightSchId == ReservationData.SelectedBookingTrips.ToArray()[1].FlightScheduleId
                            && flightDate == ReservationData.SelectedBookingTrips.ToArray()[1].FlightDate)
                        {
                            radioButton.Checked = true;
                        }
                        else
                        {
                            string clearRadioButtonscript = String.Format("<script type='text/javascript'>$(document).ready(function() {{$('#{0}').prop('checked', false);}});</script>"
                           , radioButton.ClientID);
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "clearReturnFlightRadioButtonscript", clearRadioButtonscript);
                        }
                    }
                }
            }
        }

        protected void btnNext_Click(object sender, EventArgs e)
        {  
            IEnumerable<FlightBookingTripView> trips = new List<FlightBookingTripView>();
            
            GetSelectedTrips(ref trips, lvFlightsToDest, "rdoSelectDestFlight");

            if (ReservationData.IsRoundTrip)
            {
                GetSelectedTrips(ref trips, lvReturnFlights, "rdoSelectReturnFlight");
            }

            UpdateSelectedTrips(trips);
           
            MoveToNextPage();
        }
        protected void btnPre_Click(object sender, EventArgs e)
        {
            MoveToPrePage();
        }

        private void GetSelectedTrips(ref IEnumerable<FlightBookingTripView> trips, ListView lv, string radioBtnId)
        {
            foreach (ListViewItem item in lv.Items)
            {
                var rdo = (RadioButton)item.FindControl(radioBtnId);

                if (rdo.Checked)
                {
                    long flightSchId = 0;
                    DateTime flightDate = DateTime.MinValue;
                    long.TryParse(((Label)item.FindControl("lblFlighSchedueId")).Text, out flightSchId);
                    DateTime.TryParse(((Label)item.FindControl("lblFlightDate")).Text, out flightDate);
                    IEnumerable<FlightBookingTripView> trip = FlightBookingTrips.Where(t => t.FlightScheduleId == flightSchId && t.FlightDate.Date == flightDate.Date).ToList();

                    if (trips != null && trip != null)
                    {
                        trips = trips.Union(trip);
                    }
                    break;
                }
            }
        }

        //protected List<object> FormatFlightBookingTripViewForDisplay(IEnumerable<FlightBookingTripView> tripsViews)
        //{
        //    List<object> trips = new List<object>();
        //    string mformat = "$ {0}";

        //    foreach (FlightBookingTripView t in tripsViews)
        //    {
        //        trips.Add(new
        //        {
        //            id = t.FlightBookingTripId,
        //            //desc = string.Format(format, t.TotalPrice, t.DepartureTime.ToString(@"hh\:mm"), t.DepartureCityCode, t.ArrivalTime.ToString(@"hh\:mm"), t.ArrivalCityCode, t.FlightDate.ToLongDateString(), t.Surcharge == null ? (decimal)0.00M : t.Surcharge),
        //            titleFromTo = String.Format("{0} to {1}", t.FromCity, t.ToCity),
        //            total_price = String.Format(mformat, + t.TotalPrice),
        //            from_to_time = String.Format("{0} ({1}) - {2} ({3})", t.DepartureTime.ToString(@"hh\:mm"), t.DepartureCityCode, t.ArrivalTime.ToString(@"hh\:mm"), t.ArrivalCityCode),
        //            long_date = t.FlightDate.ToLongDateString(),
        //            flight_no = "Flight: " + t.FlightNo,                   
        //            fare = "Fare (" + t.BookingTripDetailViews.Count() + " pax): " + String.Format(mformat, t.TotalPrice) + " + ",                    
        //            surcharge = "Surcharge: " + String.Format(mformat, Convert.ToDecimal(t.Surcharge).ToString("#0.00")),

        //            flightSchId = t.FlightScheduleId,
        //            flightDate = t.FlightDate.ToShortDateString()
        //        });
        //    }

        //    return trips;
        //}
        private void BindListViewData(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                string mformat = "$ {0}";
                var data = e.Item.DataItem as FlightBookingTripView;
                var lblId = e.Item.FindControl("lblId") as Label;
                var lblFlighSchedueId = e.Item.FindControl("lblFlighSchedueId") as Label;
                var lblFlightDate = e.Item.FindControl("lblFlightDate") as Label;
                var rdoSelectDestFlight = e.Item.FindControl("rdoSelectDestFlight") as RadioButton;
                var ltrTotalPrice = e.Item.FindControl("ltrTotalPrice") as Literal;
                var ltrFromToTime = e.Item.FindControl("ltrFromToTime") as Literal;
                var ltrLongDate = e.Item.FindControl("ltrLongDate") as Literal;
                var ltrFlightNo = e.Item.FindControl("ltrFlightNo") as Literal;
                var ltrFare = e.Item.FindControl("ltrFare") as Literal;
                var ltrSurcharge = e.Item.FindControl("ltrSurcharge") as Literal;

                lblId.Text = data.FlightBookingTripId.ToString();
                lblFlighSchedueId.Text = data.FlightScheduleId.ToString();
                lblFlightDate.Text = data.FlightDate.ToShortDateString();
                ltrTotalPrice.Text = String.Format(mformat, +data.TotalPrice);
                ltrFromToTime.Text = String.Format("{0} ({1}) - {2} ({3})", data.DepartureTime.ToString(@"hh\:mm"), data.DepartureCityCode, data.ArrivalTime.ToString(@"hh\:mm"), data.ArrivalCityCode);
                ltrLongDate.Text = data.FlightDate.ToLongDateString();
                ltrFlightNo.Text = "Flight: " + data.FlightNo;
                ltrFare.Text = "Fare (" + (ReservationData.NumOfAdult + ReservationData.NumOfChild) + " pax): " + String.Format(mformat, data.TotalPrice) + " + ";
                ltrSurcharge.Text = "Surcharge: " + String.Format(mformat, Convert.ToDecimal(data.Surcharge).ToString("#0.00"));
            }
        }

        protected void lvFlightsToDest_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            BindListViewData(sender, e);
        }

        protected void lvReturnFlights_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            BindListViewData(sender, e);
        }
    }
}